import React, { useEffect, useRef, useState } from 'react'
import { PageContainer } from '@ant-design/pro-layout'
import { DeleteOutlined, PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons'
import { Alert, Button, message, Popconfirm, Tooltip } from 'antd'
import ProTable from '@ant-design/pro-table'
import { delExam, detailsExam, getExamList } from '@/services/exam'
import CreateOrEdit from '@/pages/Exam/Examinations/components/CreateOrEdit'
import ProTableConfig from '@/pages/Report/ProTableConfig'
import { categoryList } from '@/services/category'
import Modal from 'antd/es/modal/Modal'
import GetTime from '@/components/GetTime'

const Index = () => {
  //添加按钮
  const [isModalVisible, setIsModalVisible] = useState(false)
  //点击修改按钮获取的ID
  const [id, setId] = useState(undefined)
  //获取考试数据
  const [examTimer, setExamTimer] = useState(false)
  //获取考试详情
  const [isDetailsExam, setIsDetailsExam] = useState([])
  const actionRef = useRef()
  //科目分类的搜索
  const [datas, setDatas] = useState([])
  //考试分类的搜索
  const [examinationSearch, setExaminationSearch] = useState([])

  const [isDelModalVisible, setIsDelModalVisible] = useState(false)

  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  //批量删除的ID
  const [ids, setIds] = useState(undefined)
  // 点击添加考试按钮显示和隐藏
  const isShowModal = async (show, id = undefined) => {
    setIsModalVisible(show)
    setId(id)

    if (id !== undefined) {
      //获取考试性情
      const response = await detailsExam(id)
      setIsDetailsExam(response)
    }
  }

  /**
   * 获取考试数据
   */
  const getExam = async (params) => {
    let response = await getExamList({
      ...params,
      include: 'subject,category',
      page: params.current,
      pageSize: params.pageSize
    })
    setExamTimer(response)
    return {
      data: response.data,
      total: response.meta.pagination.total
    }
  }

  useEffect(() => {
    //调用接口
    categoryList({ category_group: 'subject' }).then((res) => {
      //如果响应成功
      let data = {}
      res.map(item => {
        data[item.id] = {
          text: item.name,
        }
      })
      setDatas(data)
    })
    //调用接口
    categoryList({ category_group: 'examination' }).then((res) => {
      //如果响应成功
      let data = {}
      res.map(item => {
        data[item.id] = {
          text: item.name,
        }
      })
      setExaminationSearch(data)
    })

  }, [])

  /**
   * 删除考试 id
   */
  const del = async (id) => {
    let response = await delExam(id)
    if (response.status === undefined) {
      message.success('删除成功')
      setSelectedRowKeys([])
      actionRef.current.reload()
    }
  }
  /**
   * 批量删除Modal
   * @param value
   */
  const showDelModal = (value) => {
    setIds(value)
    setIsDelModalVisible(true)
  }
  /**
   * 多选操作
   * @param selectedRowKeys
   */
  const onSelectChange = selectedRowKeys => {
    setSelectedRowKeys(selectedRowKeys)
  }

  /**
   * 多选配置
   * @type {{onChange: onSelectChange, selectedRowKeys: unknown}}
   */
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  }

  /**
   * 确认删除
   */
  const handleOk = () => {
    del(ids)
    setIsDelModalVisible(false)
  }
  /**
   * 批量删除modal取消操作
   */
  const handleCancel = () => {
    setIsDelModalVisible(false)
  }

  //状态样式
  const status = [
    <Alert message="未开始" type="info" showIcon/>,
    <Alert message="进行中" type="warning" showIcon/>,
    <Alert message="已结束" type="success" showIcon/>,
  ]

  const columns = [
    {
      title: (
        <>
          ID
          <Tooltip placement="top" title="按ID排序">
            <QuestionCircleOutlined style={{ marginLeft: 4 }}/>
          </Tooltip>
        </>
      ),
      dataIndex: 'id',
      hideInSearch: 'true',
      sorter: (a, b) => a.id - b.id,
    },
    {
      title: '考试名称',
      dataIndex: 'name',
    },
    {
      title: '考试分类',
      dataIndex: 'category_id',
      valueType: 'select',
      valueEnum: examinationSearch,
      render: (_, record) => {
        return (<p>{record.category.name}</p>)
      }
    },
    {
      title: '开考时间',
      dataIndex: 'start_time',
      valueType: 'dateTime'
    },
    {
      title: '截止进考场',
      dataIndex: 'over_time',
      valueType: 'dateTime'

    },
    {
      title: '考试时长',
      dataIndex: 'timer',
      hideInSearch: 'true'
    },
    {
      title: '考试人数',
      dataIndex: 'peoples',
      hideInSearch: 'true'
    },
    {
      title: '科目',
      dataIndex: 'subject_id',
      valueType: 'select',
      valueEnum: datas,
      render: (_, record) => {
        return (<p>{record.subject.name}</p>)
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        0: {
          text: '未开始',
          status: 'Default',
        },
        1: {
          text: '进行中',
          status: 'Error',
        },
        2: {
          text: '已结束',
          status: 'Success',
        },
      },
      render: (_, record) => {
        return status[record.status]
      }
    },
    {
      title: '操作',
      hideInSearch: 'true',
      render: (_, record) => [
        <Button
          key={5}
          type="primary"
          size={'small'}
          onClick={() => isShowModal(true, record.id)}
          style={{ marginRight: '10px' }}
        >
          编辑
        </Button>,

        <Popconfirm
          key={2}
          type="primary"
          title="确定要删除吗?"
          onConfirm={() => del(record.id)}
          onCancel={()=>{message.success('已取消')}}
          okText="Yes"
          cancelText="No"
        >
          <Button
            key={3}
            type="danger"
            size={'small'}
            style={{ marginRight: '10px' }}
          >
            刪除
          </Button>
        </Popconfirm>
      ]
    }
  ]

  return (
    <PageContainer header={{
      extra: [
        <GetTime key="getTime"/>
      ]
    }}>

      <ProTable
        {
          ...ProTableConfig
        }
        actionRef={actionRef}
        columns={columns}
        request={async (params, sorter = {}) => getExam(params)}
        rowKey="id"
        rowSelection={rowSelection}
        form={{
          ignoreRules: false,
        }}
        dateFormatter="string"
        headerTitle="高级表格"
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            danger
            icon={<DeleteOutlined/>}
            onClick={() => {
              selectedRowKeys[0] ? showDelModal(selectedRowKeys) : message.error('请选择试卷')
            }}
          >
            批量删除
          </Button>,
          <Button
            key="button"
            icon={<PlusOutlined/>}
            type="primary"
            onClick={(show) => {
              isShowModal(show)
            }}
          >
            添加考试
          </Button>,
        ]}
      />
      <Modal title="删除试卷" visible={isDelModalVisible} centered={true} onOk={handleOk} onCancel={handleCancel}>
        <p>确定要删除试卷吗</p>
      </Modal>
      {!isModalVisible ? (
        ''
      ) : (
        <CreateOrEdit
          isModalVisible={isModalVisible}
          isShowModal={isShowModal}
          actionRef={actionRef}
          id={id}
          examTimer={examTimer}
          isDetailsExam={isDetailsExam}

        />
      )}
    </PageContainer>
  )
}
export default Index
